const ajaxDataForPastDays = days => {
	const results = []
	const today = new Date()

	const promises = []

	for (let i = 0; i < days; i++) {
		// 计算过去的日期
		const pastDate = new Date(today)
		pastDate.setDate(today.getDate() - i)

		const year = pastDate.getFullYear()
		const month = String(pastDate.getMonth() + 1).padStart(2, '0')
		const day = String(pastDate.getDate()).padStart(2, '0')
		const queryDate = `${year}-${month}-${day}`

		const promise = $.ajax({
			url: `/api/ip/count?queryDay=${queryDate}`,
			method: 'GET',
			dataType: 'json'
		}).then(response => {
			results.push({
				date: queryDate,
				data: response
			})
		}).catch(error => {
			console.error(`Error fetching data for ${queryDate}:`, error)
			results.push({
				date: queryDate,
				error: 'Error fetching data'
			})
		})

		promises.push(promise)
	}

	Promise.all(promises).then(() => {
		const dataArr = results.map(item => {
			const { code, data } = item.data
			
			if (code !== 200) {
				return {
					date: item.date,
					count: 0
				}
			}
			return {
				date: item.date,
				count: data.count
			}
		})

		// 根据日期重新排序数组
		const sortedDataArr = dataArr.sort((a, b) => {
			const dateA = new Date(a.date)
			const dateB = new Date(b.date)
			return dateA - dateB
		})
		
		// 获取当天的IP数据
		const todayIpCount = sortedDataArr[sortedDataArr.length - 1].count
		$('#todayIP').text(todayIpCount + '个')
		
		// 拆分数组拿到date和count
		const dateArr = sortedDataArr.map(item => item.date)
		const countArr = sortedDataArr.map(item => item.count)

		const $dashChartLinesCnt = jQuery('.js-chartjs-lines')[0].getContext('2d')
	
		const $dashChartLinesData = {
			labels: dateArr,
			datasets: [{
				label: 'IP数量',
				data: countArr,
				borderColor: '#007bff',
				backgroundColor: 'rgba(0, 123, 255, .2)',
				borderWidth: 1,
				fill: true,
				lineTension: .5
			}]
		}
	
		new Chart($dashChartLinesCnt, {
			type: 'line',
			data: $dashChartLinesData,
			options: {
				scales: {
					y: {
						ticks: {
							callback: function(value) {
								return Number.isInteger(value) ? value : ''
							}
						}
					}
				}
			}
		})
	})
}

$(document).ready(function () {
	const $landingTime = $('#landingTime')
		, $sayHello = $('#sayHello')
		, $jieshao = $('#jieshao')
		, $todayFriendsCount = $('#todayFriendsCount')
		, $cpuDom = $('#cpuDom')
		, $ramDom = $('#ramDom')
		, $cpuText = $('#cpuText')
		, $ramText = $('#ramText')
		, $advertising = $('#advertising')

	// 获取server
	const getServerFn = () => {
		const isHome = localStorage.getItem('isHome')
		
		if (isHome !== 'true') {
			return
		}
	
		$.ajax({
			type: 'GET',
			url: '/api/config/serverInfo',
			success: function (response) {
				const { code, msg, data: { cpu, mem } } = response
	
				if (code !== 200) {
					$cpuDom.css('width', '0')
					$ramDom.css('width', '0')
					$cpuText.text('0%')
					$ramText.text('0%')
					swal({
						title: '错误',
						text: msg,
						type: 'error'
					})
					return
				}
	
				$cpuDom.css('width', `${cpu}%`).attr('aria-valuenow', cpu)
				$ramDom.css('width', `${mem}%`).attr('aria-valuenow', mem)
				$cpuText.text(`${cpu}%`)
				$ramText.text(`${mem}%`)
			}
		})
	}
	
	const getServerRandomInt = () => {
		const randomNum = Math.floor(Math.random() * 100) + 1
		$cpuDom.css('width', `${randomNum}%`)
		$ramDom.css('width', `${randomNum}%`)
		$cpuText.text(`${randomNum}%`)
		$ramText.text(`${randomNum}%`)
	}

	// 进入该页面直接为首页
    localStorage.setItem('isHome', 'true')

	// 初始化数据
	getServerRandomInt()
	getServerFn()
	setInterval(() => getServerFn(), 2500)

	// 获取3天的访问ip
	ajaxDataForPastDays(3)

	const date = new Date()
	const hour = date.getHours()

	if (hour >= 6 && hour <= 11) {
		$sayHello.text('早上好🍞')
	} else if (hour >= 12 && hour <= 13) {
		$sayHello.text('中午好🍚')
	} else if (hour >= 14 && hour <= 17) {
		$sayHello.text('下午好🍮')
	} else if (hour >= 18 && hour <= 23) {
		$sayHello.text('晚上好🍺')
	} else {
		$sayHello.text('深夜好🏅')
	}

	$.ajax({
		type: 'GET',
		url: '/api/users/getUsersLoginTime',
		success: function (response) {
			const { code, msg, data: { loginTime } } = response
			if (code !== 200) {
				$landingTime.text(msg)
				return
			}
			$landingTime.text(loginTime)
		}
	})

	$.ajax({
		type: 'GET',
		url: '/api/friends/todayCount',
		success: function (response) {
			const { code, msg, data: { count } } = response
			if (code !== 200) {
				$todayFriendsCount.text(msg)
				return
			}
			
			$todayFriendsCount.text(count + '条')
		}
	})

	const xfwlUrl = 'https://www.xfabe.com/nitaiv5pro'

	$.ajax({
		type: 'GET',
		url: `${xfwlUrl}/?jieshao=520`,
		success: function (response) {
			$jieshao.html(response.jieshao)
		}
	})

	$.ajax({
		type: 'GET',
		url: `${xfwlUrl}/?banner=banner`,
		success: function (response) {
			const { code, msg, data } = response
			if (code !== 200) {
				$advertising.html(msg)
				return
			}

			if (data.length < 1) {
				$advertising.remove()
				return
			}

			const maxIndex = data.length - 1
			const randomIndex = Math.floor(Math.random() * (maxIndex + 1))

			const htmlStr = `
				<div class="card-body">
					<div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel">
						<div class="carousel-inner">
							${
								data.map((item, index) => `
									<div class="carousel-item ${index === randomIndex ? 'active' : ''}" data-bs-interval="3000">
										<a href="${item.link}" target="_blank" rel="noopener noreferrer">
											<img src="${item.img}" class="d-block w-100" alt="${item.link}">
										</a>
									</div>
								`).join('')
							}
						</div>
						<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev">
							<span class="carousel-control-prev-icon" aria-hidden="true"></span>
							<span class="visually-hidden">前</span>
						</button>
						<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next">
							<span class="carousel-control-next-icon" aria-hidden="true"></span>
							<span class="visually-hidden">后</span>
						</button>
					</div>
				</div>
			`

			$advertising.html(htmlStr)

			const carouselExampleControls = document.querySelector('#carouselExampleControls')
			new bootstrap.Carousel(carouselExampleControls, {
				interval: 3000,
				ride: 'carousel'
			})

			setTimeout(() => {
				carouselExampleControls.querySelector('button[data-bs-slide="next"]').click()
			}, 3000)
		}
	})
})